﻿using System;
using UnityEngine;

[ExecuteInEditMode]
public class ChildSimulator : MonoBehaviour
{
    [SerializeField, HideInInspector]
    private Transform lastParent;
    public Transform parent;
    [SerializeField, HideInInspector]
    private Matrix4x4 parentMatrix;
    [HideInInspector, SerializeField]
    private Vector3 startChildPosition;
    [SerializeField, HideInInspector]
    private Quaternion startChildRotationQ;
    [HideInInspector, SerializeField]
    private Vector3 startChildScale;
    [HideInInspector, SerializeField]
    private Vector3 startParentPosition;
    [HideInInspector, SerializeField]
    private Quaternion startParentRotationQ;
    [HideInInspector, SerializeField]
    private Vector3 startParentScale;

    private Vector3 DivideVectors(Vector3 num, Vector3 den)
    {
        return new Vector3(num.x / den.x, num.y / den.y, num.z / den.z);
    }

    [ContextMenu("Init")]
    public void Init()
    {
        if (this.parent != null)
        {
            this.startParentPosition = this.parent.position;
            this.startParentRotationQ = this.parent.rotation;
            this.startParentScale = this.parent.lossyScale;
            this.startChildPosition = base.transform.position;
            this.startChildRotationQ = base.transform.rotation;
            this.startChildScale = base.transform.lossyScale;
            this.startChildPosition = this.DivideVectors((Vector3) (Quaternion.Inverse(this.parent.rotation) * (this.startChildPosition - this.startParentPosition)), this.startParentScale);
        }
    }

    private void Update()
    {
        if (this.lastParent != this.parent)
        {
            this.Init();
            this.lastParent = this.parent;
        }
        if (this.parent != null)
        {
            this.parentMatrix = Matrix4x4.TRS(this.parent.position, this.parent.rotation, this.parent.lossyScale);
            base.transform.position = this.parentMatrix.MultiplyPoint3x4(this.startChildPosition);
            base.transform.rotation = (this.parent.rotation * Quaternion.Inverse(this.startParentRotationQ)) * this.startChildRotationQ;
            base.transform.localScale = Vector3.Scale(this.startChildScale, this.DivideVectors(this.parent.lossyScale, this.startParentScale));
        }
    }
}

